// 按之字形顺序打印二叉树

#include <vector>
#include <stack>
using namespace std;

struct TreeNode 
{
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution 
{
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int>> Print(TreeNode* pRoot) 
    {
        // write code here
        vector<vector<int>> ret;
        if(!pRoot) return ret;

        // st1入栈是从右往左，st2入栈是从左往右
        // 如此一来，取栈顶正好是相反的
        stack<TreeNode*> st1, st2;
        st1.push(pRoot);
        while(!st1.empty() || !st2.empty())
        {
            vector<int> v;
            while(!st1.empty())
            {
                TreeNode* top = st1.top();
                st1.pop();

                v.push_back(top->val);
                // 不为空再入栈
                if(top->left) st2.push(top->left);
                if(top->right) st2.push(top->right);
            }
            if(!v.empty()) ret.push_back(v); // 不为空再尾插
            v.clear(); // 清理数组内容，防止污染后面要尾插的数据

            while(!st2.empty())
            {
                TreeNode* top = st2.top();
                st2.pop();

                v.push_back(top->val);
                if(top->right) st1.push(top->right);
                if(top->left) st1.push(top->left);
            }
            if(!v.empty()) ret.push_back(v);
        }
        return ret;
    }
};